package bookstore;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 管理者がログインしているかどうかをチェックするフィルタです
 */
@WebFilter(filterName="AdminLoginFilter", urlPatterns="/admin/*")
public class AdminLoginFilter implements Filter {

    private static String ADMIN_LOGIN_PATH = "/adminIndex.do";

    public void init(FilterConfig config) throws ServletException {}

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException,
            ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpSession session = httpRequest.getSession(false);

        //debug
        System.out.println("Admin->doFilter");
        //debug

        if (!isLogin(session)) {
            request.getRequestDispatcher(ADMIN_LOGIN_PATH).forward(request,
                                                                   response);
        } else {
            chain.doFilter(request, response);
        }
    }

    public void destroy() {}

    private boolean isLogin(HttpSession session) {
        if (session == null) {
            return false;
        }
        Administrator admin = (Administrator) session.getAttribute(Globals.SESSION_LOGIN_ADMIN);
        if (admin == null) {
            return false;
        }
        return true;
    }
}